//统包新增和编辑页面

var RATE=Number($.cookie("ParcelRate"));
var EDITMODE=false;
var xhrVideo = new XMLHttpRequest();
(function(){
	var addForm={
		init:function(){
			myApp.showIndicator();
			this.bindEvents();
			this.loadCommon();
			myApp.hideIndicator();
		},
		bindEvents:function(){
			var self=this;
			$("#rate").text(RATE);
			//编辑
			args = GetUrlParms();				
			if(args["ID"]!=undefined){						
				ID = args["ID"];//产品ID		
				EDITMODE=true;//修改页面
			}
			if(EDITMODE){
				$(".category").hide();
				self.bindData(ID);
				$("#page_title").html(_("统包编辑"));
			}else{
				$(".category").show();
				$("#page_title").html(_("统包新增"));
			}
			//修改新增：采购人
            var html_purchaseAgent = "";
            if (list.msgcode ==true) {
                for(var k in list.msginfo){
                    html_purchaseAgent +='<option value="'+k+'">'+ _(list.msginfo[k]) +'</option>';
                }
            }
            else {
                html_purchaseAgent += "<option></option>";
            }
            $("#purchaseAgent").append(html_purchaseAgent);
			//切换主石类型
			self.changType(1);
			// self.sizeParams(1);
			$("#data_category").on("click","span",function(){
				$(this).addClass("active").siblings().removeClass("active");
				var type=$("#data_category span.active").attr("data-value");				
				self.changType(type);
			});
			//切换形状显示大小
			$("#data_shape").on("change",function(){
				var val=$(this).val();
				// self.sizeParams(val);
			});
			//关闭弹框
			$("#close_tip_btn").on("click",function(){
				$("#tip_box").hide();
			});
			//美金与人民币的转换(原)
			$("#usd_input").bind('input propertychange', function() {
				var weight=$("#_weight").val();
				var usdVal=$(this).val();
				$("#rmb_input").val(formatRMBPrice(usdVal*RATE));
				$("#rmb_inputAll").val(formatRMBPrice(usdVal*RATE*weight));
                $("#usd_inputAll").val(formatUSDPrice(usdVal*weight));

			});
			$("#rmb_input").bind('input propertychange', function() {
                var weight=$("#_weight").val();
				var rmbVal=$(this).val();
				$("#usd_input").val(formatUSDPrice(rmbVal/RATE));
				$("#usd_inputAll").val(formatUSDPrice(rmbVal/RATE*weight));
				$("#rmb_inputAll").val(formatRMBPrice(rmbVal*weight));

			});

			//采美金和人民币的转换
			$("#purchaseUSDPerGrain").bind('input propertychange',function(){
                var weight=$("#_weight").val();
                var usdVal=$(this).val();
                var purchaseRate=$("#purchaseExchange").val();
                var purchaseRMB=$("#purchaseRMB").val();
                if(usdVal && purchaseRMB!=0){
					$("#purchaseRMB").val(formatRMBPrice(usdVal*purchaseRate));
					$("#purchaseRMBAll").val(formatRMBPrice(usdVal*purchaseRate*weight));
					$("#purchaseUSDAll").val(formatUSDPrice(usdVal*weight));
				}
			})
            $("#purchaseRMB").bind('input propertychange',function(){
                var weight=$("#_weight").val();
                var rmbVal=$(this).val();
                var purchaseRate=$("#purchaseExchange").val();
                $("#purchaseUSDPerGrain").val(formatUSDPrice(rmbVal/purchaseRate));
                $("#purchaseRMBAll").val(formatRMBPrice(rmbVal*weight));
                $("#purchaseUSDAll").val(formatUSDPrice(rmbVal/purchaseRate*weight));
            });
			//通过采购汇率计算
			$("#purchaseExchange").bind('input propertychange',function(){
                var weight=$("#_weight").val();
                var purchaseRate=$(this).val();
                var usdVal=$("#purchaseUSDPerGrain").val();
                var rmbVal=$("#purchaseRMB").val();
                if(usdVal && purchaseRate){
                	$("#purchaseUSDPerGrain").val(usdVal);
					$("#purchaseRMB").val(formatRMBPrice(usdVal*purchaseRate));
					$("#purchaseRMBAll").val(formatRMBPrice(usdVal*purchaseRate*weight));
				}
                if(rmbVal!=0 && purchaseRate){
                	$("#purchaseRMB").val(rmbVal)
                    $("#purchaseUSDPerGrain").val(formatUSDPrice(rmbVal/purchaseRate));
                	$("#purchaseUSDAll").val(formatUSDPrice(rmbVal/purchaseRate*weight));
				}

			})

			//通过总重计算价格
			$("#_weight").bind('input propertychange',function(){
				var weight=$(this).val();
				var priceUSDCarat=$("#usd_input").val();
				var priceRMBCarat=$("#rmb_input").val();
				if(priceUSDCarat && priceRMBCarat){
                    $("#usd_inputAll").val(formatUSDPrice(priceUSDCarat*weight));
                    $("#rmb_inputAll").val(formatRMBPrice(priceRMBCarat*weight));
				}
				var usdPrice=$("#purchaseUSDPerGrain").val();
				var rmbPrice=$("#purchaseRMB").val();
				if(usdPrice && rmbPrice){
					$("#purchaseUSDAll").val(formatUSDPrice(usdPrice*weight));
					$("#purchaseRMBAll").val(formatRMBPrice(rmbPrice*weight));
				}
			})


			//提交验证
			$("#submit_btn").on("click",function(){
				$("#form_data").submit();
			});
			$("#reset_btn").on("click",function(){
				if(EDITMODE){
					myApp.alert(_("编辑时不能重置参数！"));
				}else{
					$("#form_data")[0].reset();
				}				
			});
            var aValidate = $("#form_data").validate({
                debug: true, //调试模式取消submit的默认提交功能   
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应  
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form
					// self.addProduct();
					self.unImg();

                },
                rules: {
                    OriginSN: "required",
                    Shape: "required",
                    Weight: "required",
                    Color: "required",
                    Clarity: "required",
                    // StyleNo: "required",
                    Price: {
					    required: true,
					    max: 1000000000
					},   
                },
                messages: {
                    OriginSN: "",
                    Shape: "",
                    Weight: "",
                    Color: "",
					Clarity: "",
					// StyleNo: "",
                    Price: {
                    	required:"",
					    max: _("价格必须小于9位数")
					  },     
                }
            });

		},
		//编辑时绑定数据
		bindData:function(ID){
		    myApp.showIndicator();//显示加载中
			var self=this;
			var submitJson={};
			submitJson.ID=ID;
			if(EDITMODE){
				submitJson.IsMyStock=true;
			}
			submitJson.GoodsType=2;
			$.ajax({
				url:'/Team/GetProductData',
				type:'POST',
				data: JSON.stringify(submitJson),
				dataType:'JSON',
				contentType: "application/json; charset=utf8",
				success:function(result){
					var res=eval('(' + result + ')')
					if(res.msgcode==true){
						var datas=res.msginfo.rows;	
						var data =datas[0];		
						self.changType(data.Category);
						//self.sizeParams(data.Shape);//显示形状对应的大小
						$("#data_category").find("span").eq(data.Category-1).addClass("active").siblings().removeClass("active");//类型的绑定
						$("#form_data").setForm(data);//帮数据
						$("#rmb_input").val(formatRMBPrice((data.Price)*RATE)); //原￥/Ct
						$("#rmb_inputAll").val(formatRMBPrice((data.Price)*RATE*(data.Weight)))  //总原价￥
						$("#usd_inputAll").val(formatUSDPrice((data.Price)*(data.Weight)))  //总原价$
						$("#purchaseUSDAll").val(formatUSDPrice((data.PurchaseUSD)*(data.Weight))) //采总价$
						$("#purchaseRMBAll").val(formatRMBPrice((data.PurchaseRMB)*(data.Weight))) //采总价￥

						$("#id_input").prop({"name":"ID","value":data.ID});//ID
						if(data.ShipTime){
							$("#data_ShipTime").val($.trim(YearDateFormats(data.ShipTime)));
						}
						if(data.PurchaseTime){
							$("#data_PurchaseTime").val($.trim(YearDateFormats(data.PurchaseTime)));//-买入时间
						}
						if(data.ArrivalTime){
							$("#data_ArrivalTime").val($.trim(YearDateFormats(data.ArrivalTime)));//到货时间
						}
						//视频绑定
						if(data.Videos!=''){
                            var _CRE_FILE = document.createElement("input");
                            _CRE_FILE.setAttribute("type", "file");
                            _CRE_FILE.setAttribute("class", "video_file");
                            _CRE_FILE.setAttribute("id", "video_input");
                            _CRE_FILE.setAttribute("style", "display:none");
                            _CRE_FILE.setAttribute("data-url",data.Videos );
                            $('.video_one').after(_CRE_FILE);
                            var videoHtml= '<section class="up-section fl close_f" style="margin-left: 5px; position: relative;width: 136px;height: 136px">'+
                                '<img src="/images/a7.png" class="close-upimg" onclick="closeVideo()" style="display: block">'+
                                '<embed src="'+data.Videos+'" style="width: 100%;height: 100%;display: block;">'+
                                '</section>';
                            $('.video_one').after(videoHtml)
						}
						
						//图片的绑定
						if(data.Images!=""){
							imgs = data.Images.split("|");
							 for (var i=0; i< imgs.length;i++) {
							 	var img_boxHmtl=[
					    			'<section class="up-section fl load">',
										'<span class="up-span"></span>',
										'<img src="/images/a7.png" class="close-upimg" style="display: block;top:4px;right:2px;width:16px;height:16px">',
										'<img src=',imgs[i],' class="up-img" data-src=',imgs[i],'>',
										'<p class="img-namep"></p>',
										'<input id="taglocation" name="taglocation" value="" type="hidden">',
										'<input id="tags" name="tags" value="" type="hidden">',
									'</section>'
					    		].join('');
					    		$("#img_box").append(img_boxHmtl);
							 }
						}
					}else{
						$("#tip_box").show();
						$("#tip_content").html(_("加载失败！"));
					}
					myApp.hideIndicator();//隐藏加载中
				}
			});
		},
        dataURLtoBlob:function(dataurl) {
			var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
			bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
			while(n--){
				u8arr[n] = bstr.charCodeAt(n);
			}
			return new Blob([u8arr], {type:mime});
		},
         unImg:function() {
			 myApp.showIndicator();
			var self=this;
			var len=$('.up-img').length;
			var formData=new FormData();
             for (var i=0;i<len;i++){
                 var dataSrc=$('.up-img').eq(i).attr('data-src');
                 if(dataSrc.indexOf('http://')==-1){
                     var blob= self.dataURLtoBlob(dataSrc);
                     formData.append("image", blob, "image" + i + ".png");
                 }

             }
			args = GetUrlParms();
			if(args["type"]!=undefined){
				TYPE = args["type"];//产品类型
			}

			if(TYPE==2){
				var upload_img_url="/team/UploadImage?type=parcels";
			}else if(TYPE==3){
				var upload_img_url="/team/UploadImage?type=inlays";
			}else if(TYPE==4){
				var upload_img_url="/team/UploadImage?type=gems";
			}else if(TYPE==5){
				var upload_img_url="/team/UploadImage?type=emeralds";
			}else if(TYPE==6){
				var upload_img_url="/team/UploadImage?type=prime-golds";
			}

			$.ajax({
				url: upload_img_url,
				data: formData,
				type: 'POST',
				cache: false,
				processData: false,
				contentType: false,
				dataType: 'JSON',
				success: function(result) {
					var _result=eval('('+result+')');
					if(_result.result==true){
                        console.log(_result.successes)
                        for(var i = 0; i < _result.successes.length; i++) {
                            $('.new_up').eq(i).attr('data-src', _result.successes[i][1]);
                        }
					}else{
						// myApp.alert(_result.msginfo);
						// $("#img_upding_now").hide();
					}
					if($('.video_file').length>0){
						self.HandVideoStr()
					}else {
                        self.addProduct();
					}

				},
				error:function(XMLHttpRequest, textStatus, errorThrown){
					myApp.alert(XMLHttpRequest.responseText);
				}

			});
		},

		//上传视频 start
        HandVideoStr:function() {
			myApp.showIndicator();
            var self=this;
            var fd = new FormData();
            var _this=document.getElementById("video_input");

            if($('#video_input').attr('data-url')){
                self.addProduct($('#video_input').attr('data-url'))
            }else {
                fd.append("fileToUpload", _this.files[0]);
                xhrVideo.onreadystatechange = function() {
                    self.videoFun();
                };
				xhrVideo.open("post", 'UploadVideo?type=parcels', true);
                xhrVideo.send(fd);
            }

        },
        videoFun:function() {
            var self=this;
            var mp4Data='';

            if(xhrVideo.readyState == 4 && xhrVideo.status == 200) {
                var obj = $.parseJSON(xhrVideo.responseText);
                var _result = eval('(' + obj + ')'); //eval()解析单个json对象
                if(_result.msgcode == false) {
                    myApp.alert(_result.msginfo);
                } else {
                    if(_result.result==false){
                        self.addProduct(mp4Data)
                    }else {

                        mp4Data=_result.successes[0][1];
                        self.addProduct(mp4Data)
                    }
                }
            }
        },
		//上传视频end
		//新增提交
		addProduct:function(mp4Data){
			//图片链接
			var images=[];
			var img_sectionLength=$(".img-section").find("section.up-section").length;
			if(img_sectionLength==0){
				myApp.alert(_("请上传图片!"));
				myApp.hideIndicator();//隐藏加载中
			}else{
				 myApp.showPreloader(_("上传中，请稍等!"));
				//获取图片地址
				for(var i=0;i<img_sectionLength;i++){
					var img_li=$(".img-section").find("section.up-section").eq(i);
					var img_src=img_li.find(".up-img").attr("data-src");
					images.push(img_src);
				}
                var imgs=images.join('|');//拼成字符串
	    		$("#Images").val(imgs);//图片
	    		$("#Category").val($("#data_category span.active").attr("data-value"));
			    var finalRes = $('#form_data').serializeArray().reduce(function(result, item){
		             result[item.name] = item.value;
		            return result;
		        }, {})//把提交的数据转为JSON格式
		        if(EDITMODE){
					finalRes.GoodsType=2;
		        	var manageURL="/Team/ModifyProductData";
		        }else{
					finalRes.GoodsType=2;
		        	var manageURL="/Team/AddProductData";
		        }
                finalRes.Videos=mp4Data||'';//视频
				 $.ajax({
				 	type:"POST",
				 	url:manageURL,
				 	data:JSON.stringify(finalRes),
				 	contentType: "application/json; charset=utf-8",
	                success: function (result) {
	                	var _result = eval('(' + result + ')');//eval()解析单个json对象
	                	myApp.hidePreloader();
	                	if(EDITMODE){
	                		var tipString=_("修改");
	                	}else{
	                		var tipString=_("新增");
	                	}
	                	if(_result.result==true){
	                		myApp.alert(tipString+_("成功！"));
	                	}else{
	                		myApp.alert(tipString+_("失败！"));
	                	}
						myApp.hideIndicator();//隐藏加载中
	                }
				 });
			}
			
		},
		//大小参数
		// sizeParams:function(val){
		// 	if(val=="1"){
		// 		var sizeHtml=[
		// 			'<option value="0.001-0.009">'+_("厘石")+'</option>',
		// 			'<option value="0.01-0.02">'+_("分石")+'</option>',
		// 			'<option value="0.03-0.07">0.05</option>',
		// 			'<option value="0.08-0.12">0.10</option>',
		// 			'<option value="0.13-0.17">0.15</option>',
		// 			'<option value="0.18-0.22">0.20</option>',
		// 			'<option value="0.23-0.29">0.25</option>',
		// 			'<option value="0.30-0.39">0.30</option>',
		// 			'<option value="0.40-0.49">0.40</option>',
		// 			'<option value="0.50-0.69">0.50</option>',
		// 			'<option value="0.70-0.99">0.70</option>',
		// 			'<option value="1.00-1.99">1.00</option>',
		// 		].join('');
		// 	}else if(val=="12" || val=="13"){
		// 		var sizeHtml=[
		// 			'<option value="1.5-1.5">1.5</option>',
         //            '<option value="2.0-2.0">2.0</option>',
         //            '<option value="2.5-2.5">2.5</option>',
         //            '<option value="3.0-3.0">3.0</option>',
         //            '<option value="3.5-3.5">3.5</option>',
         //            '<option value="4.0-4.0">4.0</option>',
         //            '<option value="4.5-4.5">4.5</option>',
         //            '<option value=">5">'+_("大于")+'5</option>',
		// 		].join('');
		// 	}else{
		// 		var sizeHtml=[
		// 				'<option value="1*2">1*2</option>',
         //                '<option value="2*2">2*2</option>',
         //                '<option value="2*4">2*4</option>',
         //                '<option value="3*5">3*5</option>',
         //                '<option value="4*6">4*6</option>',
         //                '<option value="6*8">6*8</option>',
         //                '<option value="1.5*3">1.5*3</option>',
         //                '<option value="2.5*2.5">2.5*2.5</option>',
         //                '<option value="3*3">3*3</option>',
         //                '<option value="3.5*3.5">3.5*3.5</option>',
         //                '<option value="4*4">4*4</option>',
         //                '<option value="OTHER">'+_("其他")+'</option>',
		// 			].join('');
		// 	}
		// 	$("#data_size").html(sizeHtml);
		// },
		//公共参数
		loadCommon:function(){
			//主石
			var category='';
			for (var i = 1; i < parcel_category.length; i++) {
				if(i==1){
					category += '<span data-value="'+i+'" class="active">'+_(parcel_category[i])+'</span>'
				}else{
					category += '<span data-value="'+i+'">'+_(parcel_category[i])+'</span>'
				}				
			}
			
			$("#data_category").html(category);//主石类型
			//形状
			var shape='';
			for (var i = 0; i < parcel[1].Shape.length; i++) {
				shape +='<option value="'+parcel[1].Shape[i][0]+'">'+ _(parcel[1].Shape[i][1]) +'</option>';
			}
			$("#data_shape").html(shape);
			//所在地国家
			var country='';
			for (var i = 0; i < parcel[1].Place.length; i++) {
				country +='<option value="'+parcel[1].Place[i][0]+'">'+ _(parcel[1].Place[i][1]) +'</option>';
			}
			$("#data_country").html(country);
			// //状态
			// var status='';
			// for(var i=0;i<parcel[1].Status.length;i++){
			// 	status+='<option value="'+parcel[1].Status[i][0]+'">'+_(parcel[1].Status[i][1])+'</option>';
			// }
			// $("#data_status").html(status);
			//状态
			var status='';
			for(var i=0;i<parcel[1].ReceiptStatus.length;i++){
				status+='<option value="'+parcel[1].ReceiptStatus[i][0]+'">'+_(parcel[1].ReceiptStatus[i][1])+'</option>';
			}
			$("#data_status").html(status);
			$("#submit_btn").on("click",function(){
			});
			
		},
		// 切换统包类型
		changType:function(type){
			$("#data_clarity,#data_clarityDesc").remove();
			if(type){
				//颜色
				var color='';
				for (var i = 0; i < parcel[type].Color.length; i++) {
					color += '<option value="'+parcel[type].Color[i][0]+'">'+ _(parcel[type].Color[i][1]) +'</option>'
				}
				$("#data_color").html(color);

				//大小
				var size='';
                for (var i = 0; i < parcel[type].Size.length; i++) {
                    size += '<option value="'+parcel[type].Size[i][0]+'">'+ _(parcel[type].Size[i][1]) +'</option>'
                }
                $("#data_size").html(size);

                //形状
                var shape='';
                for (var i = 0; i < parcel[type].Shape.length; i++) {
                    shape += '<option value="'+parcel[type].Shape[i][0]+'">'+ _(parcel[type].Shape[i][1]) +'</option>'
                }
                $("#data_shape_new").html(shape);


				if(type==1 || type==2){
					var clarity='<div class="form_control" id="data_clarity"><label><b class="no_null">*</b>'+_("净度")+'：</label><select name="Clarity">'
					for(var i=0;i<parcel[type].Clarity.length;i++){
						clarity+='<option value="'+parcel[type].Clarity[i][0]+'">'+_(parcel[type].Clarity[i][1])+'</option>'
					}
					clarity+='</select></div>'
					$("#data_colorDesc").after(clarity);
					var clarityDesc='<div class="form_control" id="data_clarityDesc">'+
							'<label>'+_("净度描述")+'：</label>'+
							'<textarea name="ClarityDesc"></textarea>'+
						'</div>';
					$("#data_clarity").after(clarityDesc);
				}
			}

		},
	}
	addForm.init();
})();
